{% extends "base.html" %}
{%load staticfiles%}

{% block css %}
  <link rel="stylesheet" href="{% static 'bower_components/select2/dist/css/select2.min.css' %}">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap.min.css" >
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  

{% endblock %}

{% block content %}
<!-- Content Header (Page header) -->
<section class="content-header">
    <h1>
      用户及权限
      <small>调用权限</small>
    </h1>
    <ol class="breadcrumb">
      <li><a href="/manage/token_manage"><i class="fa fa-dashboard"></i> 部门</a></li>
    </ol>
  </section>
  <div class="row">
    
    <section class="content-header">
      <div class="col-md-12">
        <button type="button" class="btn btn-success" data-toggle="modal" data-target="#appTokenModal">
            新增
        </button>
        <div class="box box-default">
          <table id="app_token_table" class="table table-striped table-bordered dataTable no-footer" >
            <thead>
              <tr>
                  <th>ID</th>
                  <th>调用应用名</th>
                  <th>token</th>
                  <th>工单前缀</th>
                  <th>工作流权限</th>
                  <th>创建人</th>
                  <th>创建时间</th>
                  <th>操作</th>
              </tr>
            </thead>
            <tbody>
      
            </tbody>
          </table>
        
        </div>
      </div>
    </section>
      <!-- /.box -->
  </div>
  </section>
      <!-- /.col -->
   
  <!-- /.content -->
  <div class="modal fade" id="appTokenModal">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">调用权限</h4>
          </div>
          <div class="modal-body">
              <form class="form-horizontal" action='/api/v1.0/accounts/app_token' method="post" id='token_form'>
                  <div class="box-body">
                    <div class="form-group">
                      <label for="inputAppName" class="col-sm-3 control-label">调用应用</label> 
                      <div class="col-sm-9">
                        <input type="text" class="form-control" id="inputAppName" placeholder="请输入调用方应用名">
                      </div>
                    </div>
                    <div class="form-group">
                      <label for="ticketSnPrefix" class="col-sm-3 control-label" data-toggle="tooltip"  title="设定该应用创建的工单流水号前缀，如前缀为loonflow,则生成的工单流水号为loonflow201901010001">工单前缀<i class="fa fa-fw fa-question"></i></label>
                      <div class="col-sm-9">
                        <input type="text" class="form-control" id="ticketSnPrefix" placeholder="如为loonflow,则生成的工单流水号为loonflow201901010001">
                      </div>
                    </div>
                    <div class="form-group">
                        <label for="workflowSelect" class="col-sm-3 control-label"  data-toggle="tooltip"  title="该应用拥有loonflow哪些工作流的操作权限:包括创建对应工作流的工单，查看工单详情等">工作流权限<i class="fa fa-fw fa-question"></i></label>
                        <div class="col-sm-9">
                          <select class="form-control select2" multiple="multiple" id="workflowSelect" data-placeholder="选择该应用有权限的工作流"
                                  style="width: 100%;">                            
                          </select>
                        </div>
                      </div>
                      <input type="text" class="form-control" id="appTokenId" style="display:none">
                  </div>
                  <!-- /.box-body -->
                  <div class="box-footer">
                    <!-- <button type="submit" class="btn btn-info pull-right">确定</button> -->
                    <input type="button" value="保存" class="btn btn-info pull-right" onclick = "submitAppToken();" />
                  </div>
                  <!-- /.box-footer -->
                </form>
          </div>
        </div>
        <!-- /.modal-content -->
      <!-- /.modal-dialog -->
    </div>
  </div>
  
</div>

<!-- /.content-wrapper -->

{% endblock %}

{% block js %}
<!-- jQuery 3 -->
<script src="{% static 'bower_components/jquery/dist/jquery.min.js' %}"></script>
<!-- Bootstrap 3.3.7 -->
<script src="{% static 'bower_components/bootstrap/dist/js/bootstrap.min.js' %}"></script>
<script src="{% static 'bower_components/select2/dist/js/select2.full.min.js' %}"></script>

<!-- AdminLTE App -->
<script src="{% static 'dist/js/adminlte.min.js' %}"></script>

<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap.min.js"></script>
<!-- <script src="../../bower_components/select2/dist/js/select2.full.min.js"></script> -->
<script>
  $(function () { $("[data-toggle='tooltip']").tooltip(); });
  $('#workflowSelect').select2({placeholderOption: "first", allowClear:true});
  $("#appTokenModal").on("hidden.bs.modal", function() {
    document.getElementById("token_form").reset(); //此操作无法清空select2中的内容
    // 以下操作都无法生效，只有trigger可以。 好坑好坑
    // $("#workflowSelect").empty(); // empty会清空所有option
    // $("#workflowSelect").select2("val", ""); 
    // $("#workflowSelect").select2("data", null); 
    // $("#workflowSelect").select2("val", ""); 
    // $('#workflowSelect').val('');
    // $('#workflowSelect').val([]);
    $("#workflowSelect").val('').trigger('change')
});
  $('#app_token_table').DataTable({
    ordering: false,
    "serverSide":true,
    "bFilter":true,
    "lengthMenu": [10, 25, 50, 100 ],
    "language": {
      "searchPlaceholder": "部门名或标签模糊搜索"
    },

    ajax: function (data, callback, settings) {
      console.log(data);
      var param = {};
      param.per_page = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
      param.page = (data.start / data.length)+1;//当前页码
      param.search_value=data.search.value;
      console.log(param);    
      $.ajax({
        type: "GET",
        url: "/api/v1.0/accounts/app_token",
        cache: false,  //禁用缓存
        data: param,  //传入组装的参数
        dataType: "json",
        success: function (result) {
          var returnData = {};
          returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
          returnData.recordsTotal = result.data.total;//返回数据全部记录
          returnData.recordsFiltered = result.data.total;//后台不实现过滤功能，每次查询均视作全部结果
          returnData.data = result.data.value;//返回的数据列表
          //console.log(returnData);
          //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
          //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
          callback(returnData);
          },
        
      })
      
    },
    columns: [
        { "data": "id"},
        { "data": "app_name" },
        { "data": "token" },
        { "data": "ticket_sn_prefix" },
        { "data": "workflow_ids", render: function(data, type, full){return '<span class="d-inline-block" tabindex="0" data-toggle="tooltip" title="Disabled tooltip">' + data + '</span>'} },
        { "data": "creator_info", render: function(data, type, full) {if(data.creator_alias){return data.creator_alias}else{return data.creator_username}}},
        { "data": "gmt_created" },
        {render: function(data, type, full){var rosJson=JSON.stringify(full).replace(/"/g, '&quot;');return ('<div><a  onclick="showEditForm(' + rosJson + ')' + '"' + '>编辑</a>|<a onclick="delAppToken(' + full.id + ')' + '"'+  '>删除</a></div>')}}
    ]
  
  })
  $( document ).ready(function() {
    // 获取工作流选项
    $.ajax({
        type: "GET",
        url: "/api/v1.0/workflows",
        cache: false,  //禁用缓存
        data: {per_page: 10000},  //传入组装的参数
        dataType: "json",
        success: function (result) {
          console.log(result);
          if (result.code===0){
            result.data.value.map(function(currentValue,index,arr){$("#workflowSelect").append("<option value=" + "'" + currentValue.id + "'" + ">" + currentValue.name + "</option>");})
            }
          }
          

          });
  });
  function submitAppToken(){
    let appTokenId = document.getElementById("appTokenId").value;
    if (!appTokenId){
      addAppToken()
    }
    else{
      // 编辑
      editAppToken();
    }
  }
  function editAppToken(){
    let appName = document.getElementById("inputAppName").value;
    let snPrefix = document.getElementById("ticketSnPrefix").value;
    let appTokenId = document.getElementById("appTokenId").value;
    let workflowSelect = document.getElementById("workflowSelect");
    let workflowArray = [];
    for(i=0;i<workflowSelect.length;i++){
        if(workflowSelect.options[i].selected){
          workflowArray.push(workflowSelect[i].value);
        }
    };
    let workflowSelerctStr = workflowArray.join(',');
    $.ajax({
        type: "PATCH",
        url: "/api/v1.0/accounts/app_token/" + appTokenId,
        cache: false,  //禁用缓存
        data: JSON.stringify({app_name: appName, ticket_sn_prefix: snPrefix, workflow_ids: workflowSelerctStr}),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
          if (result.code===0){
            // 刷新数据
            $('#app_token_table').dataTable()._fnAjaxUpdate(); 
            // 关闭modal
            $('#appTokenModal').modal('hide');
            swal({
              title: "编辑成功!",
              text: "2s自动关闭",
              icon: "success",
              showConfirmButton: false,
              timer:2000
            })
            }
          }
        });
  }

  function addAppToken(){
    let appName = document.getElementById("inputAppName").value;
    let snPrefix = document.getElementById("ticketSnPrefix").value;
    let workflowSelect = document.getElementById("workflowSelect");
    let workflowArray = [];
    for(i=0;i<workflowSelect.length;i++){
        if(workflowSelect.options[i].selected){
          workflowArray.push(workflowSelect[i].value);
        }
    }
    let workflowSelerctStr = workflowArray.join(',')
    $.ajax({
        type: "POST",
        url: "/api/v1.0/accounts/app_token",
        cache: false,  //禁用缓存
        data: JSON.stringify({app_name: appName, ticket_sn_prefix: snPrefix, workflow_ids: workflowSelerctStr}),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
          if (result.code===0){
            // 刷新数据
            $('#app_token_table').dataTable()._fnAjaxUpdate(); 
            // 关闭modal
            $('#appTokenModal').modal('hide');
            swal({
              title: "新增成功!",
              text: "2s自动关闭",
              icon: "success",
              showConfirmButton: false,
              timer:2000
            })
            }
          }
        });
  }
  function showEditForm(data){
    $("#inputAppName").attr("value",data.app_name);
    $("#ticketSnPrefix").attr("value",data.ticket_sn_prefix);
    $("#appTokenId").attr("value",data.id);
    // $("#workflowSelect").attr("value",data.workflow_ids);
    let workflow_ids_arr = data.workflow_ids.split(",");
    $("#workflowSelect").val(workflow_ids_arr).trigger("change");     
    $('#appTokenModal').modal('show');
  }
  
  function delAppToken(appTokenId){
    console.log('del token');
    console.log(appTokenId);
    swal({
      title: "是否真的要删除此记录?",
      text: "删除此记录后，通过该记录中的应用名将无权限调用loonflow的接口",
      icon: "warning",
      buttons: true,
      dangerMode: true,
    })
    .then((willDelete) => {
      if (willDelete) {
        // 删除操作
        $.ajax({
        type: "DELETE",
        url: "/api/v1.0/accounts/app_token/" + appTokenId,
        cache: false,  //禁用缓存
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
          if (result.code===0){
            // 刷新数据
            $('#app_token_table').dataTable()._fnAjaxUpdate(); 
            // 关闭modal
            swal({
              title: "删除成功!",
              text: "2s自动关闭",
              icon: "success",
              showConfirmButton: false,
              timer:2000
            })
            }
          }
        });
      }
    });
  }

</script>
{% endblock %}
